// shopController.js
const pool = require('../config/db'); // 直接使用你的 db.js 连接池

// 计算两点之间的距离（公里） - 只保留一个定义
const calculateDistance = (lat1, lon1, lat2, lon2) => {
  const R = 6371; // 地球半径（公里）
  const dLat = (lat2 - lat1) * Math.PI / 180;
  const dLon = (lon2 - lon1) * Math.PI / 180;
  const a = 
    Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * 
    Math.sin(dLon/2) * Math.sin(dLon/2); 
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
  return R * c;
};

// 获取餐厅列表
exports.getShops = async (req, res) => {
  try {
    // 1. 从 req.user 获取位置（多重容错）
    const { latitude: userLat, longitude: userLng } = req.user || {};
    
    // 2. 验证并处理位置信息（确保是有效数字）
    const finalLat = (typeof userLat === 'number' && !isNaN(userLat)) 
      ? userLat 
      : 39.9042; // 兜底：北京中心纬度
    const finalLng = (typeof userLng === 'number' && !isNaN(userLng)) 
      ? userLng 
      : 116.4074; // 兜底：北京中心经度

    console.log('用户位置（最终）:', { latitude: finalLat, longitude: finalLng });

    // 3. 获取查询参数
    const { sortBy = 'distance', serviceType = 'dinein', minRating, maxDistance, searchQuery } = req.query;

    // 4. 构建基础查询
    let query = 'SELECT * FROM shop_info WHERE is_open = true';
    const params = [];

    // 5. 添加搜索条件
    if (searchQuery) {
      query += ' AND name LIKE ?';
      params.push(`%${searchQuery}%`);
    }

    // 6. 执行查询
    const [shops] = await pool.execute(query, params);

    // 7. 计算距离并过滤
    const shopsWithDistance = shops.map(shop => {
      const distance = calculateDistance(
        finalLat, 
        finalLng, 
        parseFloat(shop.latitude) || 0, 
        parseFloat(shop.longitude) || 0
      );
      
      const isWithinDeliveryRange = serviceType === 'delivery' 
        ? distance <= (parseFloat(shop.delivery_range) || 0) 
        : true;
      const isWithinMaxDistance = maxDistance 
        ? distance <= parseFloat(maxDistance) 
        : true;
      const meetsMinRating = minRating 
        ? (parseFloat(shop.rating) || 0) >= parseFloat(minRating) 
        : true;

      return {
        ...shop,
        distance: parseFloat(distance.toFixed(2)),
        isWithinRange: isWithinDeliveryRange,
        isEligible: isWithinDeliveryRange && isWithinMaxDistance && meetsMinRating
      };
    }).filter(shop => shop.isEligible);

    // 8. 排序
    if (sortBy === 'distance') {
      shopsWithDistance.sort((a, b) => a.distance - b.distance);
    } else if (sortBy === 'rating') {
      shopsWithDistance.sort((a, b) => {
        if (b.rating !== a.rating) return b.rating - a.rating;
        return b.rating_count - a.rating_count;
      });
    }

    res.status(200).json({
      success: true,
      userLocation: { latitude: finalLat, longitude: finalLng },
      count: shopsWithDistance.length,
      data: shopsWithDistance
    });

  } catch (error) {
    console.error('获取餐厅列表失败:', error.message);
    res.status(500).json({
      success: false,
      message: '服务器错误，获取餐厅列表失败',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  }
};

// 获取单个餐厅详情
exports.getShopById = async (req, res) => {
  try {
    const [shops] = await pool.execute(
      'SELECT * FROM shop_info WHERE id = ?',
      [req.params.id]
    );
    
    if (shops.length === 0) {
      return res.status(404).json({
        success: false,
        message: '餐厅不存在'
      });
    }

    const shop = shops[0];

    // 计算用户与该餐厅的距离
    const { latitude: userLat, longitude: userLng } = req.user || {};
    
    const finalLat = (typeof userLat === 'number' && !isNaN(userLat)) 
      ? userLat 
      : 39.9042;
    const finalLng = (typeof userLng === 'number' && !isNaN(userLng)) 
      ? userLng 
      : 116.4074;

    const distance = calculateDistance(
      finalLat, 
      finalLng, 
      parseFloat(shop.latitude) || 0, 
      parseFloat(shop.longitude) || 0
    );
    
    const shopDetails = {
      ...shop,
      distance: parseFloat(distance.toFixed(2)),
      isWithinDeliveryRange: distance <= (parseFloat(shop.delivery_range) || 0),
      userLocation: { latitude: finalLat, longitude: finalLng }
    };
    
    res.status(200).json({
      success: true,
      data: shopDetails
    });
  } catch (error) {
    console.error('获取餐厅详情失败:', error.message);
    res.status(500).json({
      success: false,
      message: '服务器错误，获取餐厅详情失败',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  }
};